package com.ruoyi.combat.util;

import lombok.extern.slf4j.Slf4j;

import java.io.BufferedReader;
import java.io.File;
import java.io.InputStreamReader;
import java.util.List;
import java.util.stream.Collectors;
@Slf4j
public class CmdTask implements Runnable{
    private List<String> list;

    public CmdTask(List<String> list) {
        this.list = list;
    }
    @Override
    public void run() {
        executeCMD(list);
    }

    public void executeCMD(List<String> commands) {
        String command = handlerCMD(commands);
        log.info("异步执行CMD命令",command);
        try {

            ProcessBuilder processBuilder = new ProcessBuilder("cmd.exe", "/c", commands.get(1));
            processBuilder.directory(new File(commands.get(0)));
            processBuilder.redirectErrorStream(true);
            Process process = processBuilder.start();
            String result = new BufferedReader(new InputStreamReader(process.getInputStream())).lines().collect(Collectors.joining(System.lineSeparator()));
            log.info(result);
            process.waitFor();
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    /**
     * 处理命令行
     *
     * @param commands 使用 &&符号拼接多个命令行
     * @return 处理后的命令行
     */
    private  String handlerCMD(List<String> commands) {
        StringBuilder command = new StringBuilder();
        for (int i = 0; i < commands.size(); i++) {
            command.append(commands.get(i));
            if (i != commands.size() - 1) {
                command.append(" && ");
            }
        }
        return command.toString();
    }
}
